package cn.edu.scau.cmi.liuxintong;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.edu.scau.cmi.liuxintong.spring.ApplicationContextUtil;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class SpringHibernateSessionClient extends Application{
	static TextArea textArea = new TextArea();
	String read;
	@Override
	public void start(Stage primaryStage) throws Exception {
		// TODO Auto-generated method stub
		AnchorPane anchorPane = new AnchorPane();
		DropShadow dropshadow = new DropShadow();
		dropshadow.setColor(Color.PALEVIOLETRED);
		dropshadow.setOffsetX(5.0);
		dropshadow.setOffsetY(5.0);
		dropshadow.setRadius(10.0);
		Text experimentName = new Text("Spring管理DAO实验");//ok
		experimentName.setEffect(dropshadow);
		experimentName.setFont(Font.font(" Verdana",FontPosture.ITALIC,40));
	    String[] greetings=new String[] {"请选择实现功能","1.添加学生","2.修改学生","3.删除学生","4.添加教师"
	    ,"5.修改教师","6.删除教师","7.学生选择指导教师","8.学生修改指导教师","9.教师选择被指导的学生",
	    "10.教师修改被指导的学生","11.显示学生和教师信息"};
	    ChoiceBox<String> choiceBox = new ChoiceBox((FXCollections.observableArrayList("请选择实现功能","1.添加学生","2.修改学生","3.删除学生","4.添加教师"
	    ,"5.修改教师","6.删除教师","7.学生选择指导教师","8.学生修改指导教师","9.教师选择被指导的学生",
	    "10.教师修改被指导的学生","11.显示学生和教师信息")));
	    choiceBox.getSelectionModel().select(0);
		TextField textField = new TextField();
		textArea.setPrefHeight(330);
	    textArea.setPrefWidth(780);
	    anchorPane.getChildren().addAll(experimentName,textField,choiceBox,textArea);
		choiceBox.getSelectionModel().selectedIndexProperty().addListener(
	    		(ObservableValue<? extends Number> ov,
	    				Number old_val,Number new_val)->{
	    					switch(greetings[new_val.intValue()]) {
	    					case "请选择实现功能":
	    						textArea.appendText("请选择实现功能\n");
	    						break;
	    					case "1.添加学生":
	    						textArea.appendText("请输入要添加学生姓名:\n");
	    						read=textField.getText();
	    				           newStudent(read);
	    				           listStudents();
	    				           break;
	    					case "2.修改学生":
	    						 textArea.appendText("请输入要修改学生id和姓名:\n");
	    						 read=textField.getText();
	    				          String[] temp=read.split(" ");
	    				          changeStudent(temp[0],temp[1]);
	    				          listStudents();
	    				          break;
	    					case "3.删除学生":
	    						textArea.appendText("请输入要删除学生id:\n");
	    						 read=textField.getText();
	    				          delectStudent(read);
	    				          listStudents();
	    				          break;
	    					case "4.添加教师":
	    						textArea.appendText("请输入要添加老师姓名:\n");
	    						read=textField.getText();
	    			               newTeacher(read);
	    			               listTeachers();
	    			               break;
	    					case "5.修改教师":
	    						textArea.appendText("请输入要修改老师id和姓名:\n");
	    						read=textField.getText();
	    	                    String[] temp1=read.split(" ");
	    	                    changeTeacher(temp1[0],temp1[1]);
	    	                    listTeachers();
	    	                    break;
	    					case "6.删除教师"	:
	    						textArea.appendText("请输入要删除老师id\n");
	    						read=textField.getText();
	    		                delectTeacher(read);
	    		                listTeachers();
	    		                break;
	    					case "7.学生选择指导教师":
	    						textArea.appendText("请输入学生的id和选择老师的id\n");
	    						read=textField.getText();
	    		                   String[] temp2=read.split(" ");
	    		                   chooseTutorTeacher(temp2[0],temp2[1]);
	    		                   break;
	    					case "8.学生修改指导教师":
	    						textArea.appendText("请输入学生的id和新指导老师的id\n");//not ok
	    						read=textField.getText();
	    	                    String[] temp3=read.split(" ");
	    	                    changeTutorTeacher(temp3[0]);
	    	                    chooseTutorTeacher(temp3[0],temp3[1]);
	    			            break;	
	    					case "9.教师选择被指导的学生":
	    						textArea.appendText("请输入老师id和被指导学生id\n");
	    						read=textField.getText();
	    		                   String[] temp4=read.split(" ");
	    		                   changeBeTutorStudent(temp4[0],temp4[1]);
	    		                   break;
	    					case "10.教师修改被指导的学生":
	    						textArea.appendText("请输入老师id和需要修改被指导学生id\n");
	    						read=textField.getText();
	    	                    String[] temp5=read.split(" ");
	    	                    changeTutorStudent(temp5[0],temp5[1]);
	    	                    break;
	    					case "11.显示学生和教师信息":
	    						 listStudents();
	    			             listTeachers();
	    		                break;
	    					}
	    				});
	     AnchorPane.setLeftAnchor(experimentName, 275.0);
		 AnchorPane.setBottomAnchor(experimentName,400.0);//下
		 AnchorPane.setLeftAnchor(textField, 450.0);
		 AnchorPane.setBottomAnchor(textField,350.0);//下
		 AnchorPane.setLeftAnchor( choiceBox, 150.0);
		 AnchorPane.setBottomAnchor( choiceBox,350.0);//下
		 AnchorPane.setLeftAnchor(textArea, 10.0);
		 AnchorPane.setBottomAnchor(textArea,10.0);
		 primaryStage.setScene(new Scene(anchorPane, 800,450));
	     primaryStage.show();
	}
	public static void main(String[] args) {
		 launch(args);
	}
	
	
	public static void changeTutorStudent(String teacherId, String studentId) {//10
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
		Student student = studentDAO.findById(Long.parseLong(studentId));
		Teacher teacher=teacherDAO.findById(Long.parseLong(teacherId));
		 student.setTeacher(null);
		 studentDAO.change(student);
		 Set students=teacher.getStudents();
		 for(Object s:students) {//设置该老师指导的学生指导老师为空
		     ((Student) s).getId().equals(student.getId());
		     students.remove(s);
		     break;
		 }
		 teacher.setStudents(students);
		 teacherDAO.change(teacher);
		 transaction.commit();
	}


	public static void changeBeTutorStudent(String  teacherId, String studentId) {//9
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
		Student student=studentDAO.findById(Long.parseLong(studentId));
		Teacher teacher=teacherDAO.findById(Long.parseLong(teacherId));
		student.setTeacher(teacher);
	    studentDAO.change(student);
	    Set students=teacher.getStudents();
	    students.add(student);
	    teacher.setStudents(students);
	    teacherDAO.change(teacher);
	    transaction.commit();
	}

	public static void changeTutorTeacher(String studentId) {
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		Student student=studentDAO.findById(Long.parseLong(studentId));
		Teacher oldteacher=student.getTeacher();
		student.setTeacher(null);
		studentDAO.change(student);
	    Set oldTescherStudents=oldteacher.getStudents();
	     for(Object s:oldTescherStudents) {//设置该老师指导的学生指导老师为空
		     ((Student) s).getId().equals(student.getId());
		     oldTescherStudents.remove(s);
		     break;
		 }
	     oldteacher.setStudents(oldTescherStudents);
	     teacherDAO.change(oldteacher);
	     transaction.commit();
	}

	public static void chooseTutorTeacher(String studentId, String teacherId) {
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
	    Teacher teacher=teacherDAO.findById(Long.parseLong(teacherId));
	    Student student=studentDAO.findById(Long.parseLong(studentId));
	    student.setTeacher(teacher);
	    studentDAO.change(student);
	    Set students=teacher.getStudents();
	    students.add(student);
	    teacher.setStudents(students);
	    teacherDAO.change(teacher);
	    transaction.commit();
	}
	public static void delectTeacher(String id) {
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		Teacher teacher=teacherDAO.findById(Long.parseLong(id));
		teacherDAO.delete(teacher);
		transaction.commit();
	}
	public static void changeTeacher(String id, String name) {
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		Teacher teacher=teacherDAO.findById(Long.parseLong(id));
		teacher.setName(name);
		teacherDAO.change(teacher);
		 transaction.commit();
	}
	public static void newTeacher(String name) {
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		Transaction transaction = teacherDAO.getSession().beginTransaction();
		Teacher teacher=new Teacher();
		teacher.setName(name);
		teacherDAO.save(teacher);
		transaction.commit();
	}
	public static void delectStudent(String id) {
		 ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
	      StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
	      Transaction transaction = studentDAO.getSession().beginTransaction();
	      Student student=studentDAO.findById(Long.parseLong(id));
	      studentDAO.delete(student);
	      transaction.commit();
	}
	public static void changeStudent(String id, String name) {
		  ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
	      StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
	      Transaction transaction = studentDAO.getSession().beginTransaction();
	      Student student=studentDAO.findById(Long.parseLong(id));
	      student.setName(name);
	      studentDAO.change(student);
	      transaction.commit();
	}
	public static void newStudent(String read) {
		  ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
	      StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
	      Transaction transaction = studentDAO.getSession().beginTransaction();
	      Student student=new Student();
          student.setName(read);
          studentDAO.save(student);
	      transaction.commit();
	    }
	public static void listStudents() {
		textArea.appendText("学生名单为：\n");
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
	    StudentDAO studentDAO=(StudentDAO)((BeanFactory) ac).getBean("StudentDAO");
		List students=studentDAO.findAll();
		Iterator<?> studentIterator = students.iterator();
		while(studentIterator.hasNext()){
			  Student student = (Student) studentIterator.next();
			  if(student.getTeacher()!=null) {
				  textArea.appendText("学生的ID号是："+student.getId()+"学生的名字是："+student.getName()+"学生指导老师"+student.getTeacher().getId()+"\n");	  
		      }
			  else {
				  textArea.appendText("学生的ID号是："+student.getId()+"学生的名字是："+student.getName()+"学生指导老师"+student.getTeacher()+"\n");
		      }
		}
	}
	public static void listTeachers() {
		textArea.appendText("老师名单为：\n");
		ApplicationContext ac = ApplicationContextUtil.getSpringHibernateSession();
		TeacherDAO teacherDAO=(TeacherDAO)((BeanFactory) ac).getBean("TeacherDAO");
		List teachers=teacherDAO.findAll();
		Iterator<?> teacherIterator = teachers.iterator();
		 while(teacherIterator.hasNext()){
			 Teacher teacher = (Teacher) teacherIterator.next();
			 textArea.appendText("老师的ID号是："+teacher.getId()+"老师的名字是："+teacher.getName()+"老师指导的学生:");
	 	     Set students=teacher.getStudents();
	 	      if(students.size()!=0) {
	 	    	   for(Object s:students) {//设置该老师指导的学生指导老师为空
	 	    		  textArea.appendText(((Student) s).getId()+" ");
			 }
	 	      }
	 	      else textArea.appendText("null");
	 	     textArea.appendText("\n");
	 	    }
		 }
}

